package artid.com.arttogoa.view;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.NetUtils;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：HandwritingBoard_View   
 * 类描述   ：手写板自定义View   
 * 创建人   ：耿卫斌   
 * 创建时间：2016-12-21 上午10:36:36   
 *
 */
public class HandwritingBoard_View extends View {
	private Bitmap mBitmap;
	private Bitmap bitmap;
	private Canvas mCanvas;
	private Path mPath;
	private int y =0;
	private DisplayMetrics dm ;
	private Paint mBitmapPaint;// 画布的画笔
	private Paint mPaint;// 真实的画笔
	private float mX, mY;// 临时点坐标
	// 保存Path路径的集合,用List集合来模拟栈，用于后退步骤
	private static List<DrawPath> savePath;
	// 保存Path路径的集合,用List集合来模拟栈,用于前进步骤
	private static List<DrawPath> canclePath;
	// 记录Path路径的对象
	private DrawPath dp;
	private int screenWidth, screenHeight;// 屏幕長寬
	private class DrawPath {
		public Path path;// 路径
		public Paint paint;// 画笔
	}
	private int bgColor=Color.parseColor("#FFFFFF");
	//笔的颜色
	public int paintColor = Color.parseColor("#000000");
	//笔的粗细
	public int srokeWidth = 15;

	/**
	 * 得到画笔
	 * @return
	 */
	public Paint getPaint() {
		return mPaint;
	}
	/**
	 * 设置画笔
	 * @param mPaint
	 */
	public void setPaint(Paint mPaint) {
		this.mPaint = mPaint;
	}

	private void init(Context mContext) {
		//这里因为布局问题所以相应的截取一部分
		screenWidth = Integer.parseInt(NetUtils.getDisplayMetrics((Activity)mContext).get(NetUtils.DM_WIDTH))-NetUtils.dip2px(mContext, 60);
		screenHeight =Integer.parseInt(NetUtils.getDisplayMetrics((Activity)mContext).get(NetUtils.DM_HEIGHT))-NetUtils.dip2px(mContext, 40);
		mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,Bitmap.Config.ARGB_8888);
		// 保存一次一次绘制出来的图形
		mCanvas = new Canvas(mBitmap);
		mBitmapPaint = new Paint(Paint.DITHER_FLAG);
		mCanvas.drawColor(bgColor);
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);// 设置外边缘
		mPaint.setStrokeCap(Paint.Cap.ROUND);// 形状
		mPaint.setStrokeWidth(srokeWidth);// 画笔宽度
		mPaint.setColor(paintColor);
		savePath = new ArrayList<DrawPath>();
		canclePath = new ArrayList<DrawPath>();
	}

	private void initPaint(){
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);// 设置外边缘
		mPaint.setStrokeCap(Paint.Cap.ROUND);// 形状
		mPaint.setStrokeWidth(srokeWidth);// 画笔宽度
		mPaint.setColor(paintColor);
	}


	public HandwritingBoard_View(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);	
		if (bitmap!=null) {
			bitmap.recycle();
			mBitmap.recycle();
			bitmap=null;
			mBitmap=null;
		}
		init(context);

	}

	public HandwritingBoard_View(Context context, AttributeSet attrs) {
		super(context, attrs);
		dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);	
		if (bitmap!=null) {
			bitmap.recycle();
			mBitmap.recycle();
			bitmap=null;
			mBitmap=null;
		}
		init(context);
	}


	public HandwritingBoard_View(Context context, int w, int h) {
		super(context);
		dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);	
		if (bitmap!=null) {
			bitmap.recycle();
			mBitmap.recycle();
			bitmap=null;
			mBitmap=null;
		}
		init(context);
	}

	@Override
	public void onDraw(Canvas canvas) {
		try {
			// 将前面已经画过得显示出来
			canvas.drawBitmap(mBitmap, 0, 0, null);
			if (mPath != null) {
				// 实时的显示
				canvas.drawPath(mPath, mPaint);
			}
		} catch (Exception e) {
			// TODO: handle exception
			if (savePath != null && savePath.size() > 0) {
				fn(screenWidth,screenHeight);
				// 移除最后一个path,相当于出栈操作
				Iterator<DrawPath> iter = savePath.iterator();		//重复保存
				while (iter.hasNext()) {
					DrawPath drawPath = iter.next();
					mCanvas.drawPath(drawPath.path, drawPath.paint);
				}
				invalidate();// 刷新
			}
			Log.d("log", "重新绘画写字板错误："+e.toString());
		}
	}

	/**
	 * 撤销的核心思想就是将画布清空， 将保存下来的Path路径最后一个移除掉， 重新将路径画在画布上面。
	 */
	public int revoke() {
		fn(screenWidth,screenHeight);
		// 清空画布，但是如果图片有背景的话，则使用上面的重新初始化的方法，用该方法会将背景清空掉…
		if (savePath != null && savePath.size() > 0) {
			// 移除最后一个path,相当于出栈操作
			savePath.remove(savePath.size() - 1);
			Iterator<DrawPath> iter = savePath.iterator();		//重复保存
			while (iter.hasNext()) {
				DrawPath drawPath = iter.next();
				mCanvas.drawPath(drawPath.path, drawPath.paint);
			}
			invalidate();// 刷新
		}else{
			return -1;
		}
		return savePath.size();
	}

	/**
	 * 重做的核心思想就是将撤销的路径保存到另外一个集合里面(栈)， 然后从redo的集合里面取出最顶端对象， 画在画布上面即可。
	 */
	public int redo() {
		// 如果撤销你懂了的话，那就试试重做吧。
		if(canclePath.size()<1)
			return canclePath.size();
		mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,Bitmap.Config.ARGB_8888);
		mCanvas.setBitmap(mBitmap);// 重新设置画布，相当于清空画布
		mCanvas.drawColor(bgColor);
		// 清空画布，但是如果图片有背景的话，则使用上面的重新初始化的方法，用该方法会将背景清空掉…
		if (canclePath != null && canclePath.size() > 0) {
			// 移除最后一个path,相当于出栈操作
			DrawPath  dPath = canclePath.get(canclePath.size() - 1);
			savePath.add(dPath);
			canclePath.remove(canclePath.size() - 1);
			Iterator<DrawPath> iter = savePath.iterator();
			while (iter.hasNext()) {
				DrawPath drawPath = iter.next();
				mCanvas.drawPath(drawPath.path, drawPath.paint);
			}
			invalidate();// 刷新
		}
		return canclePath.size();
	}

	/**
	 * 清楚画布
	 * @param width
	 * @param height
	 * @return
	 */
	public int clear() {
		fn(screenWidth,screenHeight);
		// 清空画布，但是如果图片有背景的话，则使用上面的重新初始化的方法，用该方法会将背景清空掉…
		if (savePath != null && savePath.size() > 0) {
			// 移除最后一个path,相当于出栈操作
			savePath.clear();
			Iterator<DrawPath> iter = savePath.iterator();		//重复保存
			while (iter.hasNext()) {
				DrawPath drawPath = iter.next();
				mCanvas.drawPath(drawPath.path, drawPath.paint);
			}
			invalidate();// 刷新
		}else{
			return -1;
		}
		return savePath.size();
	}
	
	public int getSavePath(){
		return savePath.size();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:

			initPaint();
			//重置下一步操作
			canclePath = new ArrayList<DrawPath>();
			// 每次down下去重新new一个Path
			mPath = new Path();
			// 每一次记录的路径对象是不一样的
			dp = new DrawPath();
			touch_start(x, y);
			invalidate();
			break;
		case MotionEvent.ACTION_MOVE:
			touch_move(x, y);
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			touch_up();
			invalidate();
			break;
		}
		return true;
	}

	private void touch_start(float x, float y) {
		mPath.moveTo(x, y);
		mX = x;
		mY = y;
	}

	private void touch_move(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(mY - y);
		if (dx >= 4 || dy >= 4) {
			// 从x1,y1到x2,y2画一条贝塞尔曲线，更平滑(直接用mPath.lineTo也是可以的)
			mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			mX = x;
			mY = y;
		}
	}

	private void touch_up() {
		mPath.lineTo(mX, mY);
		mCanvas.drawPath(mPath, mPaint);
		// 将一条完整的路径保存下来(相当于入栈操作)
		dp.path = mPath;
		dp.paint = mPaint;
		savePath.add(dp);
		mPath = null;// 重新置空
	}
	
	public Bitmap getBitmap(){
		mBitmap= BitmapUtil.rotateBitmapByDegree(mBitmap, 270);
		return mBitmap;
	}

	public void saveImage(){
		String path = Environment.getExternalStorageDirectory()+ "/YJB/handwritingBoard.png";
		try {
			BitmapUtil.saveBitmapToFile(mBitmap, path);
		} catch (Exception e) {
			Log.d("log", "保存图片错误："+e);
		}
	}



	Bitmap bm1;
	Bitmap bp ;
	Bitmap bitmap2=null;
	public Bitmap BitmapAmplification(String path) {
		if (bitmap2!=null) {
			bitmap2.recycle();
			bitmap2=null;
			if (bitmap!=null) {
				bitmap=null;
			}
			if (bm1!=null) {
				bm1=null;
			}

			if (bp!=null) {
				bp=null;
			}
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		bm1 =BitmapFactory.decodeFile(path, options);
		int scu = (int)options.outWidth/550;
		if (scu<=0) {//小于零
			scu=1;
		}
		options.inSampleSize = scu;
		options.inJustDecodeBounds = false;
		bitmap2 = BitmapFactory.decodeFile(path, options);
		if (bitmap2!=null) {
			int w = bitmap2.getWidth();	//得到图片的宽度
			int h = bitmap2.getHeight();//得到图片的高度
			Log.v("log", "手写板："+"宽"+w+"高"+h);
			float ww = ((float) dm.widthPixels) / w;
			float hh = ((float) dm.heightPixels) / h;
			Matrix matrix = new Matrix();
			matrix.postScale(ww, hh);
			Log.v("log", "手写板：可以使用");
			Bitmap bp = Bitmap.createBitmap(bitmap2, 0, 0, w, h, matrix, true);
			if (!bitmap2.isRecycled()&&bitmap2!=null) {
				bitmap2.recycle();
				bitmap2= null;
				Log.v("log", "手写板：回收");
				System.gc();
			}
			return bp;
		}
		return null;
	}

	public void fn(int w,int h){
		screenWidth = w;
		screenHeight =h;
		mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,Bitmap.Config.ARGB_8888);
		// 保存一次一次绘制出来的图形
		mCanvas = new Canvas(mBitmap);
		mBitmapPaint = new Paint(Paint.DITHER_FLAG);
		mCanvas.drawColor(bgColor);
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);// 设置外边缘
		mPaint.setStrokeCap(Paint.Cap.ROUND);// 形状
		mPaint.setStrokeWidth(srokeWidth);// 画笔宽度
		mPaint.setColor(paintColor);
	}

	int k = 7;
	public void UPdataColor(int i){
		if (i==1) {
			if (mPaint==null) {
				initPaint();
			}

		}else if (i==2) {



		}else if (i==3) {


		}else if (i==4) {
			k=k+3;
			mPaint.setStrokeWidth(k);
		}		
	}

}
